package com.lanou.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lanou.entity.TbItem;
import com.lanou.mapper.TbItemMapper;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by QuChao on 2018/11/19
 * <p>
 * 通过传递过来的条件参数进行数据库tb_item表查询
 * 再将查询结果插入到Redis中
 */
public class ItemSetRedis implements Runnable {
    private TbItemMapper tbItemMapper;
    private JedisPool jedisPool;
    private Integer startPage;
    private Integer rows;

    public ItemSetRedis(TbItemMapper tbItemMapper, JedisPool jedisPool, Integer startPage, Integer rows) {
        this.tbItemMapper = tbItemMapper;
        this.jedisPool = jedisPool;
        this.startPage = startPage;
        this.rows = rows;
    }

    @Override
    public void run() {
        Map<String, Object> map = new HashMap<>();
        map.put("startPage", startPage);
        map.put("rows", rows);
        List<TbItem> tbItemList = tbItemMapper.selectByStartPageRows(map);
        for (TbItem tbItem : tbItemList) {
            Jedis jedis = jedisPool.getResource();
            String jsonString = JSON.toJSONString(tbItem, SerializerFeature.WriteClassName);
            jedis.set("item" + tbItem.getId(), jsonString);
            System.out.println("item" + tbItem.getId());
            jedis.close();
        }

    }
}
